package com.ruoyi.client.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.client.pojo.vo.ChapterVo;
import com.ruoyi.client.pojo.vo.NovelVo;
import com.ruoyi.client.service.NovelDetailService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Anonymous//允许匿名访问
@CrossOrigin
@RestController
@RequestMapping("/novels")
public class NovelDetailController {

    @Resource
    NovelDetailService detailService;

    @GetMapping("/detail")
    public AjaxResult detail(@RequestParam long novel_id){
        // 增加小说阅读量
        detailService.incrementViewCount(novel_id);
        
        NovelVo novelVo=detailService.listDetailId(novel_id);
        return AjaxResult.success(novelVo);
    }

    @GetMapping("/chapter_detail")
    public AjaxResult chapter_detail(@RequestParam long chapter_id){
        ChapterVo chapterVo=detailService.chapterDetailId(chapter_id);
        return AjaxResult.success(chapterVo);
    }
    
    /**
     * 检查用户是否已点赞该小说
     * @param novelId 小说ID
     * @return 点赞状态
     */
    @GetMapping("/checkLike/{novelId}")
    public AjaxResult checkLike(@PathVariable("novelId") Long novelId) {
        try {
            // 检查用户是否登录
            StpUtil.checkLogin();
            Long userId = StpUtil.getLoginIdAsLong();
            
            boolean isLiked = detailService.checkUserLike(userId, novelId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("isLiked", isLiked);
            
            return AjaxResult.success(result);
        } catch (Exception e) {
            // 未登录用户返回未点赞状态
            Map<String, Object> result = new HashMap<>();
            result.put("isLiked", false);
            return AjaxResult.success(result);
        }
    }
    
    /**
     * 切换点赞状态（点赞/取消点赞）
     * @param novelId 小说ID
     * @return 操作结果
     */
    @PostMapping("/like/{novelId}")
    public AjaxResult toggleLike(@PathVariable("novelId") Long novelId) {
        try {
            // 检查用户是否登录
            StpUtil.checkLogin();
            Long userId = StpUtil.getLoginIdAsLong();
            
            boolean isLiked = detailService.toggleLike(userId, novelId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("isLiked", isLiked);
            result.put("message", isLiked ? "点赞成功" : "已取消点赞");
            
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("操作失败：" + e.getMessage());
        }
    }
    
}